﻿using AutoMapper;
using MediatR;
using PublicClass;
using PublicClass.BreedingEnum;
using S.Breeding.Domain;
using S.Breeding.Infrastructure;
using S.Breeding.Read.Api.Application.Command.SheepWeighCommand;

namespace S.Breeding.Read.Api.Application.CommandHandlers.SheepWeighCommandHandlers
{
    public class SheepWeighListCommandHandlers : IRequestHandler<SheepWeighListCommand, PageInfo<SheepWeigh>>
    {

        private readonly IRepository<SheepWeigh> repository;
        private readonly PageInfo<SheepWeigh> pageInfo;
        private readonly IMapper mapper;
        public SheepWeighListCommandHandlers(IRepository<SheepWeigh> repository, PageInfo<SheepWeigh> pageInfo, IMapper mapper)
        {
            this.repository = repository;
            this.pageInfo = pageInfo;
            this.mapper = mapper;
        }

        public async Task<PageInfo<SheepWeigh>> Handle(SheepWeighListCommand request, CancellationToken cancellationToken)
        {
            var list = repository.All().Result.Where(x => !x.IsDel);
            if (!string.IsNullOrEmpty(request.Earbugles))
            {
                list = list.Where(x => x.Earbugles == request.Earbugles);
            }
            if (request.Sdate != null)
            {
                list = list.Where(x => x.WeighDate >= request.Sdate);
            }
            if (request.Edate != null)
            {
                list = list.Where(x => x.WeighDate <= request.Edate);
            }
            if (request.WeightType > 0)
            {
                list = list.Where(x => x.WeightType == request.WeightType);
            }
            if (request.Breed > 0)
            {
                list = list.Where(x => x.Breed == request.Breed);
            }
            if (request.Sex > 0)
            {
                list = list.Where(x => x.Sex == request.Sex);
            }

            if (request.SWeighMonth != null)
            {
                list = list.Where(x => x.WeighMonth <= request.SWeighMonth);
            }
            if (request.EWeighMonth != null)
            {
                list = list.Where(x => x.WeighMonth >= request.EWeighMonth);
            }

            pageInfo.totalCount = list.Count();
            pageInfo.pageCount = (int)Math.Ceiling(pageInfo.totalCount * 1.0 / request.pageSize);
            list = list.OrderByDescending(x=>x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            return new PageInfo<SheepWeigh>()
            {
                datas = list.ToList(),
                totalCount = pageInfo.totalCount,
                pageCount = pageInfo.pageCount,
            };
        }
    }
}
